/////////////////////////////////////////////////////////////////////////
//
// Amuse Engine SDK - core/threads
// Copyright (c) 2014.  All Rights Reserved
//
// File:		AEThread_posix.cpp
// Author:		Gianluca Belardelli
// Date:		01/06/2014
//
/////////////////////////////////////////////////////////////////////////
#include <AECore.h>
#include <core\threads\AEThread.h>

AEThread::AEThread( void )
{
	m_lpThread = 0;
	m_uiThreadID = 0;
}

AEThread::~AEThread( void )
{
	//if( m_lpThread )
		//CloseHandle( m_lpThread );
}

AEINT32 AEThread::StartThread( AEStartFunction *lpfnFunction, void *lpParam, const char *lpName, int nThreadStackSize )
{
	pthread_attr_t ptAttr;
	AEINT32 nRes;

	nRes = pthread_attr_init( &ptAttr );
	if( nRes != 0 )
		return -1;

	if( nThreadStackSize > 0 )
	{
		nRes = pthread_attr_setstacksize( &ptAttr, nThreadStackSize );
		if( nRes != 0 )
		{
			pthread_attr_destroy( &ptAttr );
			return -1;
		}
	}

	nRes = pthread_create( &m_lpThread, &ptAttr, lpfnFunction, lpParam );

	pthread_attr_destroy( &ptAttr );

	if( nRes != 0 )
		return -1;

	m_uiThreadID = (AEUINT32)m_lpThread;

	return m_uiThreadID;
}

void AEThread::JoinThread( void )
{
	AEASSERT_MSG( m_lpThread != 0, "Thread non inizializzato" );

	AEUINT32 uiResult;
	pthread_join( m_lpThread, (void **)&uiResult );

}

AEThread::AEThreadStatus AEThread::GetStatus( void ) const
{
	if( m_uiThreadID == 0 )
		return AETHREAD_NOT_STARTED;

	return AETHREAD_RUNNING;
}

AETHREADHANDLE AEThread::GetThreadHandle( void ) const
{
	return m_lpThread;
}

